package spring.cloud.tasks.tasks_manager.task_item_assign.pick_up.executor;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import spring.cloud.tasks.common.curator.Curator;
import spring.cloud.tasks.common.task_item_allot.Executor;
import spring.cloud.tasks.common.task_item_allot.TaskItem;
import spring.cloud.tasks.tasks_manager.task_item_assign.PreferExecutorSettings;
import spring.cloud.tasks.tasks_manager.task_item_assign.pick_up.PickUp;

import java.util.Iterator;
import java.util.List;

/**
 * executor下线，摘取该executor运行的所有非本地模式任务，移除该executor
 */
@Slf4j
@Setter
@Getter
public class PickUpWhenExecutorOffline extends PickUp {
    private String executorId;


    @Override
    protected void log() {
        log.info("Execute the {} with {} offline", this.getClass().getSimpleName(), executorId);
    }

    /**
     * 失去流量同时下线
     */
    @Override
    public boolean pickUp(Curator curator,//
                          List<String> taskIdList,//
                          List<String> enableTaskIdList,//
                          List<TaskItem> pickUpEdTaskItemList,//
                          List<TaskItem> discardTaskItemList,//
                          List<Executor> onlineExecutorList,//
                          List<Executor> ownTrafficOnlineExecutorList,//
                          PreferExecutorSettings preferExecutorSettings) throws Exception {
        /**
         * 摘取下线的executor全部Shard
         */
        Executor targetOnlineExecutor = null;
        Iterator<Executor> iterator = onlineExecutorList.iterator();
        while (iterator.hasNext()) {
            Executor onlineExecutor = iterator.next();
            if (onlineExecutor.getExecutorId().equals(executorId)) {
                targetOnlineExecutor = onlineExecutor;
                iterator.remove();
                pickUpEdTaskItemList.addAll(onlineExecutor.getTaskItemList());
                break;
            }
        }

        if (targetOnlineExecutor != null) {
            Iterator<Executor> $iterator = ownTrafficOnlineExecutorList.iterator();
            while ($iterator.hasNext()) {
                Executor onlineExecutor = $iterator.next();
                if (targetOnlineExecutor.equals(onlineExecutor)) {
                    $iterator.remove();//移掉引用
                    break;
                }
            }
        }
        // 如果该executor实际上已经在此之前下线，则摘取失败
        return targetOnlineExecutor != null;
    }


}
